/*初始化函数*/
function init() {
    let layer = layui.layer;
    $.get("/role/info", {"token": localStorage.getItem("token")}, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<tr><td><input type="radio" name="role_id" value="' + n.id + '" title="' + n.name + '"></td>';
                html_str += '<td>' + n.name + '</td>';
                html_str += '<td>' + n.userNumber + '</td>';
                html_str += '<td>' + n.description + '</td></tr>';
            })
            $("#role_list").html(html_str);
            $("input[name='role_id'][title='root']").prop("disabled", true)
                .parent().mouseenter(function () {
                layer.tips("root角色不能修改和删除", this, {tips: 2})
            }).mouseleave(function () {
                layer.closeAll("tips");
            });
            $("input[name='role_id'][title='publisher']").prop("disabled", true)
                .parent().mouseenter(function () {
                layer.tips("publisher角色不能修改和删除", this, {tips: 2})
            }).mouseleave(function () {
                layer.closeAll("tips");
            });
            $("input[name='role_id'][title='personal']").prop("disabled", true)
                .parent().mouseenter(function () {
                layer.tips("personal角色不能修改和删除", this, {tips: 2})
            }).mouseleave(function () {
                layer.closeAll("tips");
            });
        } else if (result.code === 401)
            window.parent.location.href = "/login.html";
        else layer.msg(result.msg, {icon: 5});
    })
    layer.closeAll("loading");
}

layui.use(['layer', 'form'], function () {
    let layer = layui.layer, form = layui.form;
    // 1.增加按钮
    $("#add_btn").click(function () {
        let add_layer_index = layer.open({
            type: 1,
            title: "增加",
            content: $("#add_edit_layer"),
            closeBtn: 2,
            //anim: 3,
            success: function (layero, index) {
                $("#reset_btn").click();//清空值
                $("div[name='user_number_div']").prop("hidden", true);
                $("#add_edit_layer").prop("hidden",false);
            },
            end: function () {
                $("#add_edit_layer").prop("hidden",true).attr("style","");
            }
        })
        // 1.1提交按钮
        form.on('submit(form_submit)', function (data) {
            //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            let insert_load_index = layer.load(1);
            $.post("/role", {
                "token": localStorage.getItem("token"),
                "name": $.trim(data.field.name),
                "description": $.trim(data.field.description)
            }, function (result) {
                if (result.code === 200) {
                    let html_str = "";
                    html_str += '<tr><td><input type="radio" name="role_id" value="' + result.data.id + '"></td>';
                    html_str += '<td>' + result.data.name + '</td>';
                    html_str += '<td>' + result.data.userNumber + '</td>';
                    html_str += '<td>' + result.data.description + '</td></tr>';
                    $("#role_list").prepend(html_str);
                    layer.close(add_layer_index);
                } else
                    layer.msg(result.msg, {icon: 5});
                layer.close(insert_load_index);
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    })

    // 2.修改按钮
    $("#edit_btn").click(function () {
        let $role_checked = $("input[type='radio'][name='role_id']:checked");
        if ($role_checked.length !== 1) {
            layer.msg("请选择需要修改的角色", {icon: 5});
            return false;
        }
        let edit_layer_index = layer.open({
            type: 1,
            title: "修改",
            content: $("#add_edit_layer"),
            closeBtn: 2,
            //anim: 3,
            success: function (layero, index) {
                edit_init($role_checked.val());//修改前初始化值
                $("#add_edit_layer").prop("hidden",false);
            },
            end: function () {
                $("#add_edit_layer").prop("hidden",true).attr("style","");
            }
        })
        // 2.1提交按钮
        form.on('submit(form_submit)', function (data) {
            //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            let update_load_index = layer.load(1);
            $.ajax({
                url: "/role",
                method: "PUT",
                data: {
                    "token": localStorage.getItem("token"),
                    "id": $role_checked.val(),
                    "name": $.trim(data.field.name),
                    "description": $.trim(data.field.description)
                },
                dataType: "JSON",
                success: function (result) {
                    if (result.code === 200) {
                        let html_str = "";
                        html_str += '<tr><td><input type="radio" name="role_id" value="' + result.data.id + '"></td>';
                        html_str += '<td>' + result.data.name + '</td>';
                        html_str += '<td>' + result.data.userNumber + '</td>';
                        html_str += '<td>' + result.data.description + '</td></tr>';
                        $role_checked.parent().parent().after(html_str).remove();
                        layer.close(edit_layer_index);
                    } else
                        layer.msg(result.msg, {icon: 5});
                    layer.close(update_load_index);
                }
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    })

    // 3.删除按钮
    $("#delete_btn").click(function () {
        let $role_checked = $("input[type='radio'][name='role_id']:checked");
        if ($role_checked.length !== 1) {
            layer.msg("请选择需要删除的角色", {icon: 5});
            return false;
        }
        layer.confirm("确认删除" + $role_checked.parent().next().html() + "角色吗", {icon: 3, title: "警告"}, function (index) {
            let delete_load_index = layer.load(1);
            $.ajax({
                url: "/role",
                method: "delete",
                data: {"token": localStorage.getItem("token"),
                "id":$role_checked.val()},
                dataType: "json",
                success: function (result) {
                    if (result.code === 200) {
                        $role_checked.parent().parent().remove();
                        layer.close(index);
                        layer.msg(result.msg, {icon: 1});
                    } else
                        layer.msg(result.msg, {icon: 5});
                    layer.close(delete_load_index);
                }
            })
        })
    })

    // 开始初始化
    init();
})

/*修改前的初始化值*/
function edit_init(role_id) {
    let edit_load_index = layer.load(1);
    $.get("/role/info",
        {
            "token": localStorage.getItem("token"),
            "id": role_id
        },
        function (result) {
            if (result.code === 200) {
                $("input[name='name']").val(result.data.name);
                $("input[name='description']").val(result.data.description);
                $("input[name='user_number']").val(result.data.userNumber);
                $("div[name='user_number_div']").prop("hidden", false);
                $("#reset_btn").prop("disabled", true).addClass("layui-btn-disabled");
            } else
                layer.msg(result.msg, {icon: 5});
            layer.close(edit_load_index);
        })
}